<template>
  <div class="article-lists">
    <el-card class="!border-none" shadow="never">
      <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
        <!-- <el-form-item label="产品分类">
          <el-select class="w-80" v-model="queryParams.cate_id" placeholder="请选择" clearable filterable >
            <el-option v-for="item in optionsData.product_cate_list" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>  -->
        <el-form-item label="银行">
          <el-select class="w-80" v-model="queryParams.bank_code" placeholder="请选择" clearable filterable >
            <el-option v-for="item in optionsData.bank_list" :key="item.bank_code" :label="item.name" :value="item.bank_code" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称">
          <el-input class="w-[280px]" v-model="queryParams.name" clearable />
        </el-form-item> 
        <el-form-item label="产品编码">
          <el-input class="w-[280px]" v-model="queryParams.sn" clearable />
        </el-form-item>
        <el-form-item label="产品状态">
          <el-select class="w-[280px]" v-model="queryParams.is_online">
            <el-option label="全部" value/>
            <el-option label="已上架" :value="1"/>
            <el-option label="已下架" :value="0"/>
          </el-select>
        </el-form-item> 
        <el-form-item label="所属城市">
            <el-select-v2
                v-model="queryParams.area_id"
                filterable
                clearable
                :options="optionCity"
                placeholder="请选择"
                class="w-[280px]"
                :height="280"
              />
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never">
      <div>
        <router-link v-perms="['product.product/add', 'product.product/add:edit']" :to="{ path: getRoutePath('product.product/add:edit') }">
          <el-button type="primary" class="mb-4">
            <template #icon>
              <icon name="el-icon-Plus"/>
            </template>
            <span>新增产品</span>
          </el-button>
        </router-link>
      </div>
      <el-table size="large" v-loading="pager.loading" :data="pager.lists">
        <el-table-column label="序号(ID)" prop="id" min-width="90"/>
        <el-table-column label="所属城市" prop="area_id" min-width="110" >
					<template #default="{ row }">
            <span v-if="row.is_nationwide">全国</span>
						<span v-else-if="row.area_id" v-city="row.area_id"></span>
						<span v-else>平台</span>
					</template>
				</el-table-column>
        <el-table-column label="产品ID" min-width="190" prop="sn"/>
        <el-table-column label="产品分类" prop="cate_name" min-width="160" />
        <el-table-column label="银行" prop="bank_name" min-width="190" /> 
        <el-table-column label="产品名称" prop="name" min-width="160" /> 
        <el-table-column label="产品logo" min-width="160">
          <template #default="{ row }">
            <image-contain v-if="row.logo" :src="row.logo" :width="60" :height="45" :preview-src-list="[row.logo]" preview-teleported fit="contain" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="最高额度(万)" prop="quota" min-width="160" show-tooltip-when-overflow/> -->
		<el-table-column label="最高额度(万)" min-width="160">
			<template #default="{ row }">{{row.quota/10000}}</template>
		</el-table-column> 
        <el-table-column label="授信期限" min-width="200">
          <template #default="{ row }">
            <el-tag  v-for="(item, index) in row.credit_year" :key="index" type="info" size="small">{{item==1?'1个月':item==2?'2个月':item==3?'3个月':item==6?'6个月':item==12?'1年':item==24?'2年':item==36?'3年':item==60?'5年':item==120?'10年':item==240?'20年':item==360?'30年':''}}</el-tag>
          </template>
        </el-table-column> 
        <el-table-column label="利率类型" min-width="160">
          <template #default="{ row }"> {{ row.rate_type == 1 ? '年化利率' : '日化利率' }} </template>
        </el-table-column> 
        <el-table-column label="利率值" min-width="160">
          <template #default="{ row }">
            {{ row.rate_type == 1 ? ((parseInt(row.rate_start * 10000)/100).toString() + '%') : ((parseInt(row.rate_start * 100000)/100).toString() + '‰') }}
            -
            {{ row.rate_type == 1 ? (parseInt(row.rate_end * 10000)/100).toString() + '%' : (parseInt(row.rate_end * 100000)/100).toString() + '‰' }}
          </template>
        </el-table-column> 
        <el-table-column label="还款方式" min-width="160">
          <template #default="{ row }"> {{ localGetRepaymentTypeText(row.repayment_type) }} </template>
        </el-table-column> 
        <el-table-column label="准入区域" min-width="160">
          <template #default="{ row }"> {{ localGetAccessAreasText(row.access_area_arr) }} </template>
        </el-table-column> 
        <el-table-column label="收佣比例" min-width="160">
          <template #default="{ row }"> {{(row.commission_rate *100).toString()+'%' }} </template>
        </el-table-column>
        <el-table-column label="状态" min-width="160">
          <template #default="{ row }">
             <span  v-if="row.is_online == 0" style="color:red"> 已下架 </span>
            <span  v-if="row.is_online == 1"> 已上架 </span>
          </template>
        </el-table-column> 
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button v-perms="['product.product/edit', 'product.product/add:edit']" type="primary" link >
              <router-link :to="{ path: getRoutePath('product.product/add:edit'), query: { id: row.id, area_id: row.area_id } }">编辑</router-link>
            </el-button>
            <el-button v-perms="['product.product/delete']" type="danger" link @click="handleDelete(row.id, row.area_id)">删除</el-button>
            <el-switch v-perms="['product.product/updateStatus']" v-model="row.is_online" :active-value="1" :inactive-value="0" @change="changeStatus($event, row.id, row.area_id)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <pagination v-model="pager" @change="getLists"/>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" setup name="productLists">
import {productLists, productDelete, productStatus, productCate} from '@/api/product/product';
import {getNextLevelAreaList, getBankList} from "@/api/app";
import {usePaging} from '@/hooks/usePaging';
import {getRoutePath} from '@/router';
import feedback from '@/utils/feedback';
import {useDictOptions} from "@/hooks/useDictOptions";
import {isEmpty} from "@/utils/util";
import useAppStore from '@/stores/modules/app'
const useApp = useAppStore()
const optionCity:any = useApp.optionCity;

const queryParams = reactive({
  cate_id: '',
  bank_code: '',
  name: '',
  sn: '',
  is_online: '',
  area_id: ''
})

const {pager, getLists, resetPage, resetParams} = usePaging({
  fetchFun: productLists,
  params: queryParams
})

const {optionsData} = useDictOptions<{
  // product_cate_list: any[],
  bank_list: any[]
}>({
  // product_cate_list: {
  //   api: productCate,
  // },
  bank_list: {
    api: getBankList
  }
})

const changeStatus = async (is_online: any, id: number, area_id:String) => {
  await feedback.confirm(is_online == 0?"下架之后，用户和渠道将不能看到该产品，是否确认下架？":is_online == 1?"上架之后，用户和渠道可看到该产品，是否确认上架?":'').then(async()=>{
  	try {
  	  await productStatus({id, is_online, area_id})
  	  getLists()
  	} catch (error) {
  	  getLists()
  	}
  }).catch(()=>{
  	getLists()
  });
}

const handleDelete = async (id: number,area_id:String) => {
  await feedback.confirm('确定删除该产品？')
  await productDelete({id,area_id})
  getLists()
}

const localGetRepaymentTypeText = (repaymentTypes: number[]| null): string => {
  //1.先息后本 2.等额本息 3.等额本金 4.一次性还本付息 5.随借随还
  let repaymentTypeStr = ''
  if (!isEmpty(repaymentTypes)) {
    (repaymentTypes as number[]).forEach((item,index )  => {
      if (item == 1) {
        repaymentTypeStr += '先息后本/'
      } else if (item == 2) {
        repaymentTypeStr += '等额本息/'
      } else if (item == 3) {
        repaymentTypeStr += '等额本金/'
      } else if (item == 4) {
        repaymentTypeStr += '一次性还本付息/'
      } else if (item == 5) {
        repaymentTypeStr += '随借随还/'
      }

    })
  }
  return repaymentTypeStr.slice(0, -1)
}


const localGetAccessAreasText = (accessAreaArr: Array<any>): string => {
  let accessAreaText = ''
  accessAreaArr.forEach((item, index) => {
    accessAreaText += (item?.Name)+'/'
  })
  return accessAreaText.replace(/[\\//]$/, "");
}

onActivated(() => {
  getLists()
})

getLists()
</script>
